package com.keller.seckill.service;

import com.keller.seckill.exception.GlobalException;
import com.keller.seckill.mapper.LoginMapper;
import com.keller.seckill.pojo.User;
import com.keller.seckill.utils.CookieUtil;
import com.keller.seckill.utils.MD5Util;
import com.keller.seckill.utils.UUIDUtil;
import com.keller.seckill.vo.LoginVo;
import com.keller.seckill.vo.RespBean;
import com.keller.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
@Slf4j
public class LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public RespBean login(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        //校验密码
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        User user = loginMapper.selectById(mobile);
        log.info("user is {}", user);
        if(null == user){
            throw new GlobalException(RespBeanEnum.SESSION_ERROR);
        }

        if(null == user.getPassword() || !MD5Util.formPassToDBPass(password, user.getSalt()).equals(user.getPassword())){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //生成cookie
        String ticket = UUIDUtil.uuid();
        redisTemplate.opsForValue().set("user:"+ticket, user);
        CookieUtil.setCookie(request, response,"userTicket", ticket);
        return RespBean.success(ticket);
    }

    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(userTicket)) {
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        if (user != null) {
            CookieUtil.setCookie(request, response, "userTicket", userTicket);
        }
        return user;
    }
}
